package com.example.kotlinExample.exception.handler

import com.example.kotlinExample.enum.ResultCode
import com.example.kotlinExample.exception.ApiException
import com.example.kotlinExample.vo.ResultVO
import io.lettuce.core.RedisCommandTimeoutException
import org.springframework.data.redis.RedisConnectionFailureException
import org.springframework.validation.BindException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice


@RestControllerAdvice
class ExceptionControllerAdvice {

    @ExceptionHandler(Exception::class)
    fun exceptionHandler(e: Exception):ResultVO<String?> {
        e.printStackTrace()
        return ResultVO(ResultCode.ERROR, e.message)
    }

    @ExceptionHandler(RedisConnectionFailureException::class, RedisCommandTimeoutException::class)
    fun redisConnectionFailureException(e: RedisConnectionFailureException) = ResultVO(ResultCode.CONNECTION_TIMEOUT,
            ResultCode.CONNECTION_TIMEOUT.msg)

    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun methodArgumentNotValidExceptionHandler(e: MethodArgumentNotValidException): ResultVO<String> {
        val objectError = e.bindingResult.allErrors[0]
        return ResultVO(ResultCode.FAILED, objectError.defaultMessage!!)
    }

    @ExceptionHandler(BindException::class)
    fun bindExceptionHandler(e: BindException): ResultVO<String> {
        val objectError = e.bindingResult.allErrors[0]
        return ResultVO(ResultCode.FAILED, objectError.defaultMessage!!)
    }

    @ExceptionHandler(ApiException::class)
    fun apiExceptionHandler(e: ApiException) = ResultVO(ResultCode.ERROR, e.msg)

}